package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.SexEnum;
import com.tanhua.dubbo.mapper.UserMapper;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class MyCenterService {

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UserApi userApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private TanHuaService tanHuaService;

    @DubboReference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private SettingsService settingsService;

    @Autowired
    private BlackListService blackListService;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired
    private QuestionService questionService;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    /**
     * 更新用户资料
     *
     * @param userInfoVo
     * @return
     */
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        UserInfo userInfo = BeanUtil.toBeanIgnoreError(userInfoVo, UserInfo.class);
        userInfo.setUserId(UserThreadLocal.get());
        userInfo.setSex(StrUtil.equals("man", Convert.toStr(userInfoVo.getGender())) ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        return this.userInfoApi.update(userInfo);
    }

    /**
     * 读取用户资料
     *
     * @param userId
     * @return
     */
    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get();
        }
        //查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);
        if (StrUtil.isEmpty(Convert.toStr(userInfo))) {
            return null;
        }
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
        return userInfoVo;
    }

    public Boolean isLike(Long userId) {
        return this.userLikeApi.isLike(UserThreadLocal.get(), userId);
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public CountsVo queryCounts() {
        Long userId = UserThreadLocal.get();
        CountsVo countsVo = new CountsVo();
        countsVo.setFanCount(this.userLikeApi.queryFanCount(userId));
        countsVo.setLoveCount(this.userLikeApi.queryLikeCount(userId));
        countsVo.setEachLoveCount(this.userLikeApi.queryMutualLikeCount(userId));
        return countsVo;
    }


    public PageResult queryBlacklist(Integer page, Integer pageSize) {
        Long user = UserThreadLocal.get();

        IPage<BlackList> blackListIPage = this.blackListService.queryBlacklist(user, page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(Convert.toInt(blackListIPage.getTotal()));
        pageResult.setPages(Convert.toInt(blackListIPage.getPages()));

        List<BlackList> records = blackListIPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<Object> userIds = CollUtil.getFieldValues(records, "blackUserId");
//        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIds);
        List<BlackListVo> blackListVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            BlackListVo blackListVo = new BlackListVo();
            blackListVo.setAge(userInfo.getAge());
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setId(userInfo.getUserId());
            blackListVo.setNickname(userInfo.getNickName());

            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    public void delBlacklist(Long userId) {
        Long user = UserThreadLocal.get();
        this.blackListService.delBlacklist(user, userId);
    }

    public SettingsVo querySettings() {
        SettingsVo settingsVo = new SettingsVo();
        Long userId = UserThreadLocal.get();

        //设置用户的基本信息
        settingsVo.setId(userId);
        User user = userMapper.selectById(userId);
        settingsVo.setPhone(user.getMobile());

        //查询用户的配置数据
        Settings settings = this.settingsService.querySettings(userId);
        if (ObjectUtil.isNotEmpty(settings)) {
            settingsVo.setGonggaoNotification(settings.getGonggaoNotification());
            settingsVo.setLikeNotification(settings.getLikeNotification());
            settingsVo.setPinglunNotification(settings.getPinglunNotification());
        }

        //查询陌生人问题
        settingsVo.setStrangerQuestion(this.tanHuaService.queryQuestion(userId));

        return settingsVo;
    }

    public void saveQuestions(String content) {
        Long userId = UserThreadLocal.get();
        this.questionService.save(userId, content);
    }


    /**
     * 查询相互喜欢列表
     *
     * @param type
     * @param page
     * @param pageSize
     * @param nickName
     * @return
     */
    public PageResult queryLikeList(String type, Integer page, Integer pageSize, String nickName) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        List<Object> userIdList = new ArrayList<>();
        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (type) {
            case "1":
                PageInfo<UserLike> userLikePageInfo = this.userLikeApi.queryMutualLikeList(Convert.toLong(userId), page, pageSize);
                userIdList = CollUtil.getFieldValues(userLikePageInfo.getRecords(), "likeUserId");

                break;
            case "2":
                PageInfo<UserLike> userLikePageInfoList = this.userLikeApi.queryLikeList(Convert.toLong(userId), page, pageSize);
                userIdList = CollUtil.getFieldValues(userLikePageInfoList.getRecords(), "likeUserId");
                break;
            case "3":
                PageInfo<UserLike> queryFanList = this.userLikeApi.queryFanList(Convert.toLong(userId), page, pageSize);
                userIdList = CollUtil.getFieldValues(queryFanList.getRecords(), "userId");
                break;
            case "4":
                PageInfo<Visitors> visitorsPageInfoList = this.userLikeApi.queryMyVisitorList(Convert.toLong(userId), page, pageSize);
                userIdList = CollUtil.getFieldValues(visitorsPageInfoList.getRecords(), "visitorUserId");
                break;
        }
        System.out.println(userIdList);
        if (CollUtil.isEmpty(userIdList)) {
            return pageResult;
        }

        List<UserInfo> userInfoList = this.userInfoApi.queryUserInfoList(userIdList, nickName);
        System.out.println(userInfoList);
        System.out.println(userIdList);


        List<UserLikeListVo> userLikeListVoList = new ArrayList<>();
        for (Object uid : userIdList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equal(uid, userInfo.getUserId())) {
                    UserLikeListVo userLikeListVo = new UserLikeListVo();
                    userLikeListVo.setId(userInfo.getId());
                    userLikeListVo.setAge(userInfo.getAge());
                    userLikeListVo.setAvatar(userInfo.getLogo());
                    userLikeListVo.setCity(userInfo.getCity());
                    //是否喜欢
                    userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(userId, userInfo.getUserId()));
                    userLikeListVo.setEducation(userInfo.getEdu());
                    userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
                    userLikeListVo.setMarriage(StrUtil.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
                    userLikeListVo.setNickname(userInfo.getNickName());
                    userLikeListVo.setMatchRate(Convert.toInt(this.recommendUserApi.queryScore(userId, userInfo.getUserId())));


                    userLikeListVoList.add(userLikeListVo);
                }
            }
        }
        pageResult.setItems(userLikeListVoList);


        return pageResult;
    }


    /**
     * 喜欢-取消
     *
     * @param userId
     */
    public void deleteLike(Long userId) {
        this.userLikeApi.notLikeUser(UserThreadLocal.get(), userId);
    }

    /**
     * 粉丝-喜欢
     *
     * @param userId
     */
    public void likeFans(Long userId) {
        this.userLikeApi.likeUser(UserThreadLocal.get(), userId);
    }

}